<template>
  <el-scrollbar>
    <div class="person_center">
      <el-form :label-width="formLabelWidth" label-position="top">
        <el-upload
          class="avatar-uploader"
          :action="'http://'+serverIp+':9090/file/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <el-form-item label="用户名">
          <el-input
            v-model.trim="form.username"
            disabled
            autocomplete="off"
            placeholder="请输入用户名"
            style="width: 50%"
            clearable
          />
        </el-form-item>

        <el-form-item label="昵称">
          <el-input
            v-model.trim="form.nickname"
            autocomplete="off"
            placeholder="请输入昵称"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model.trim="form.email"
            autocomplete="off"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="电话">
          <el-input
            v-model.trim="form.phone"
            autocomplete="off"
            placeholder="请输入电话"
          />
        </el-form-item>
        <el-form-item label="地址">
          <el-cascader
            placeholder="请输入地址"
            size="large"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange"
            clearable
            filterable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button>重置</el-button>
          <el-button type="primary" @click="save_info"> 确认 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-scrollbar>
</template>


<script>
//Element UI 中国省市区级联数据
//regionData 省市区三级联动（不带“全部”选项）
//CodeToText是个大对象，属性是区域码，属性值是汉字 用法例如：CodeToText['110000']输出北京市
import { serverIp } from '../../../public/config'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  name: 'MyPerson',
  emits: ['refreshUser'],
  data() {
    return {
      serverIp:serverIp,
      //中国省市区级
      options: regionData,
      selectedOptions: [],
      //表单label的长度
      formLabelWidth: '80px',

      form: {
        username: '',
        nickname: '',
        email: '',
        address: '',
        phone: '',
        avatarUrl: '',
        provinceCode: '',
        cityCode: '',
        areaCode: ''
      },
      user: localStorage.getItem('user')
        ? JSON.parse(localStorage.getItem('user'))
        : {}
    }
  },
  //① 当组件 在内存中被创建完毕之后，会自动调用 created 函数
  created() {
    this.selectedOptions = [
      this.form.provinceCode,
      this.form.cityCode,
      this.form.areaCode
    ]

    //resful风格
    // this.$http.get('/user/' + this.newuser.id).then((res) => {
    //   console.log('个人中心数据类型' + typeof res) //object
    //   console.log(res)
    //   this.form = res.data
    //   if (this.form.address != '') {
    //     // console.log(typeof res.address)
    //     console.log(this.form.address)
    //     // 强制转化成字符串
    //     this.handleTest(this.form)
    //   } else {
    //     this.selectedOptions = []
    //     console.log('数据库地址为空：' + this.selectedOptions)
    //   }
    // })

    this.getUser().then((res) => {
      console.log(res)
      console.log('个人中心数据类型' + typeof res) //object
      this.form = res
      if (this.form.address != '') {
        // console.log(typeof res.address)
        console.log(this.form.address)
        // 强制转化成字符串
        this.handleTest(this.form)
      } else {
        this.selectedOptions = []
        console.log('数据库地址为空：' + this.selectedOptions)
      }
    })
  },

  methods: {
    // 新增数据
    save_info() {
      this.$http.post('/user', this.form).then((res) => {
        if (res.status === '200') {
          this.$message.success('保存成功')
          //触发父级更新User的方法
          this.$emit('refreshUser')
          //更新浏览器存储的用户信息
          this.getUser().then((res) => {
            res.token = JSON.parse(localStorage.getItem('user')).token
            localStorage.setItem('user', JSON.stringify(res))
          })
        } else {
          this.$message.error('保存失败')
        }
      })
    },

    handleChange(value) {
      if (value != null) {
        console.log(value)
        console.log(
          CodeToText[value[0]],
          CodeToText[value[1]],
          CodeToText[value[2]]
        )
        this.form.provinceCode = value[0]
        this.form.cityCode = value[1]
        this.form.areaCode = value[2]
        this.form.address =
          CodeToText[value[0]] +
          '/' +
          CodeToText[value[1]] +
          '/' +
          CodeToText[value[2]]

        console.log('页面选择:' + this.form.address)
      } else {
        this.form.address = ''
      }
    },

    handleTest(newdata) {
      var str = newdata.address + ''
      var index = str.indexOf('/')
      var last = str.lastIndexOf('/')
      var provinceCode = TextToCode[str.slice(0, index)].code
      var cityCode =
        TextToCode[str.slice(0, index)][str.slice(index + 1, last)].code
      var areaCode =
        TextToCode[str.slice(0, index)][str.slice(index + 1, last)][
          str.slice(last + 1)
        ].code
      this.selectedOptions = [provinceCode, cityCode, areaCode]
      console.log('数据库：' + this.selectedOptions)
    },
    //上传成功
    handleAvatarSuccess(res) {
      this.form.avatarUrl = res
      this.$message.success('上传成功')
    },

    //获取用户列表
    async getUser() {
      const { data: res } = await this.$http.get('/user/' + this.user.id)
      console.log(res)
      return res
    }
  }
}
</script>

<style lang="less" scoped>
.person_center {
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 2px 0 6px rgb(0 21 41 / 35%);
  border-radius: 20px;
  padding: 30px 0;

  .el-form {
    width: 40%;
    // background-color: #fff;
    .el-form-item {
      // background-color: skyblue;
      width: 100%;
    }
  }
}
//   输入框
/deep/ .el-form-item__content {
  width: 440px;
  height: 40px;
  line-height: 40px;
}
/deep/ .el-input {
  height: 100%;
}
</style>

<style>
.avatar-uploader {
  margin-bottom: 10px;
}
.avatar-uploader .avatar {
  width: 158px;
  height: 158px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 20px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 158px;
  height: 158px;
  text-align: center;
}
</style>